#include "client.h"
#include "ui_client.h"
#include <QtNetwork>

Client::Client(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Client)
{
    ui->setupUi(this);

    tcpSocket = new QTcpSocket(this);
    connect(tcpSocket, &QTcpSocket::readyRead, this, &Client::readMessage);
    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(displayError(QAbstractSocket::SocketError)));
    //定时器，生成并发送测试数据
    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this, SLOT(onTimeout()));
    bconnect = false;

    //定时器，生成并发送测试数据
    timer1 = new QTimer(this);
    connect(timer1,SIGNAL(timeout()),this, SLOT(onTimeout1()));

}

Client::~Client()
{
    delete ui;
}

void Client::newConnect()
{
    // 初始化数据大小信息为0
    blockSize = 0;

    // 取消已有的连接
    tcpSocket->abort();
    tcpSocket->connectToHost(ui->hostLineEdit->text(),
                             ui->portLineEdit->text().toInt());
    bconnect = true;
    // 用于暂存要发送的数据
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);

    // 设置数据流的版本，客户端和服务器端使用的版本要相同
    out.setVersion(QDataStream::Qt_5_6);
    out << (quint16)0;
    out << "hello TCP Server!!!";
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));
    QString senddata;
    senddata = "hello TCP Server,I'm TCP Client";
    tcpSocket->write(senddata.toLatin1());
}

void Client::readMessage()
{
//    QDataStream in(tcpSocket);
//    // 设置数据流版本，这里要和服务器端相同
//    in.setVersion(QDataStream::Qt_5_6);

//    // 如果是刚开始接收数据
//    if (blockSize == 0) {
//        //判断接收的数据是否大于两字节，也就是文件的大小信息所占的空间
//        //如果是则保存到blockSize变量中，否则直接返回，继续接收数据
//        if(tcpSocket->bytesAvailable() < (int)sizeof(quint16)) return;
//        in >> blockSize;
//    }
//    // 如果没有得到全部的数据，则返回，继续接收数据
//    if(tcpSocket->bytesAvailable() < blockSize) return;
//    // 将接收到的数据存放到变量中
//    in >> message;
    QByteArray recvdata = tcpSocket->read(40);
    message = QString(recvdata);
    // 显示接收到的数据
    ui->messageLabel->setText(message);
    ui->textEdit_2->setText(message);
}

void Client::displayError(QAbstractSocket::SocketError)
{
    qDebug() << tcpSocket->errorString();
}

void Client::on_connectButton_clicked()
{
    newConnect();
}

void Client::on_pushButton_clicked()
{
    QString Qsendbuf;
    Qsendbuf = ui->textEdit->toPlainText();
    tcpSocket->write(Qsendbuf.toLatin1());
}
void Client::onTimeout()
{
    if(!bconnect) return;
    QString senddata;
    senddata += "LD,";
    QString Qdata;
    Qdata += ",";
    qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
    for(int var =0; var < 1290;++var)
    {
        Qdata += QString::number(qrand()%(200) +400);
        Qdata += ",";
    }
    int datalength = Qdata.length() + 7;

    senddata += QString("%1").arg(datalength,5,10,QLatin1Char('0'));
    senddata += Qdata;
    int ncrc = CRCCheck((unsigned char*)senddata.data(), senddata.length());
//    unsigned int hcrc = ncrc / 256;
//    unsigned int lcrc = ncrc % 256;
    ncrc %= 10000;

    //Qmycrc.sprintf("%c%c",(unsigned char)hcrc, (unsigned char)lcrc);
    senddata += QString("%1").arg(ncrc,4,10,QLatin1Char('0'));;
    senddata += ",ED";
    tcpSocket->write(senddata.toLatin1());
}

void Client::onTimeout1()
{
    if(!bconnect) return;
    QString senddata1;
    senddata1 += "01,03";
    senddata1 += ",06,";
    senddata1 += "CL1,12345,CU1,12345,CL2,12345,CU2,12345,CL3,12345,CU3,12345,000000,ED";
    tcpSocket->write(senddata1.toLatin1());

}
unsigned int Client::CRCCheck(unsigned char* pp, unsigned int crclen)
{
    unsigned char a;
    unsigned int i, j;
    unsigned int CRC16 = 0xa001;   //密钥
    //unsigned int crc = 0xffff;
    unsigned int crc = 0;
    for (i = 0; i<crclen; i++)
    {
//        crc ^= pp[i];
//        for (j = 0; j<8; j++)
//        {
//            a = crc & 0x0001;
//            crc >>= 1;
//            if (a)
//            {
//                crc ^= CRC16;
//            }
//        }
        crc += (int)pp[i];

    }

    return crc;
}
